#include<bits/stdc++.h>

using namespace std;

const int maxt = 4000005;
int n, m, t, ti, ans = INT_MAX, cnt[maxt], sum[maxt], f[maxt];

int main() {
    cin >> n >> m;
    
    for (int i = 1; i <= n; i++) {
        cin >> ti;
        t = max(t, ti);
        cnt[ti]++;
        sum[ti] += ti;
    }
    
    for (int i = 1; i < t + m; i++) {
        cnt[i] += cnt[i - 1];
        sum[i] += sum[i - 1];
    }
    
    for (int i = 0; i < t + m; i++) {
        f[i] = cnt[i] * i - sum[i];
        
        for (int j = 0; j <= i - m; j++) {
            f[i] = min(f[i], f[j] + (cnt[i] - cnt[j]) * i - (sum[i] - sum[j]));
        }
    }
    
    for (int i = t; i < t + m; i++) {
        ans = min(ans, f[i]);
    }
    
    cout << ans << endl;
    
    return 0;
}

